/**
 * 随机密码库，生成算法
 */

#include <stdio.h>
#include <string.h>
// #include <RandomNative.h>
//=========================================================
unsigned long long seed; // 种子
const unsigned long long multiplier = 0x5DEECE66DL;
const unsigned long long addend = 0xBL;
const unsigned long long mask = (1ULL << 48) - 1;

//===================
void setSeed(int seedVal);
void getSequence(char *name, int no);
int nextInt(int n);
int next(int bits);
void print(int *seq);
//=========================================================
int main(int argc, char const *argv[])
{
    int seed = 100000019; // 种子
    int count = 87616;
    setSeed(seed); //设置种子
    printf("创建密码数组[%d个]：\n", count);
    getSequence("", count);
}
//=========================================================
void setSeed(int seedVal)
{
    seed = seedVal;
}
/**
 * 对给定数目的自0开始步长为1的数字序列进行乱序
 * @param name 数组名称
 * @param count  给定数目
 * @return 乱序后的数组
 */
void getSequence(char *name, int count)
{
    int seq[64] = {};
    int a = 64, b = count / a, c = 0, d = 10, e = 0;
    for (; e < d; e++)
    {
        for (int i = 1 + e; i < b + 1; i += d)
        {
            for (; c < a; c++)
            {
                seq[c] = i + b * c;
            }
            c = 0;
            //============================
            for (int y = 0; y < 64; y++)
            {
                int p = nextInt(64);
                if (p == y)
                {
                    y--;
                    continue;
                }
                seq[y] ^= seq[p];
                seq[p] ^= seq[y];
                seq[y] ^= seq[p];
            }
            // print("[64]"seq);
            putFlashData(name, seq); //TODO 分段将 seq存储到flash
        }
    }
}

int nextInt(int n)
{
    if (n <= 0)
    {
        printf("n must be positive");
        return 0;
    }
    int bits, val;
    do
    {
        // printf("nextInt:%d-%d\n", seed, bits - val + (n - 1));
        bits = next(31);
        val = bits % n; //考虑离散性
    } while (bits - val + (n - 1) < 0);
    return val;
}

int next(int bits)
{
    seed = (seed * multiplier + addend);
    return seed;
}

void print(int *seq)
{
    for (size_t i = 0; i < 64; i++)
    {
        printf("%d ", seq[i]);
    }
    printf("\n\n");
}